package com.lfy.generator.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lfy.generator.bean.Table;
import com.lfy.generator.common.ResponsePageDto;
import com.lfy.generator.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: 李丰翼
 * @DateTime: 2020/11/7 0007 10:29
 * @Description: 代码生成controller
 */
@Controller
public class GeneratorController {
    @Autowired
    private GeneratorService generatorService;

    @RequestMapping("/genCode")
    @ResponseBody
    public void genCode(String[] tables, HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject jsonObject = new JSONObject(request.getParameter("json-data"));
        HashMap<String, String> settting = JSONUtil.toBean(jsonObject, HashMap.class);
        byte[] bytes = generatorService.generatorCode(settting, tables);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(bytes, response.getOutputStream());

    }

    @PostMapping("list")
    @ResponseBody
    public ResponsePageDto<List<Table>> list(@RequestBody HashMap<String, String> map) {
        try {
            List<Table> list = generatorService.list(map.get("dataSource.url"), map.get("dataSource.user"), map.get("dataSource.pass"));
            return ResponsePageDto.success(list, list.size());
        } catch (Exception e) {
            return ResponsePageDto.failed("数据库参数错误");
        }


    }


}
